const express = require('express');
const bodyParser = require('body-parser');
const mysql = require('mysql2/promise'); // 使用promise版本的mysql2

const app = express();
const port = 3000;

// 使用 body-parser 中间件
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// 数据库连接配置 - 请根据你的Navicat配置修改
const dbConfig = {
  host: 'localhost',
  port: 3306,
  user: 'root', // 你的数据库用户名
  password: '123456', // 你的数据库密码
  database: 'flash_sale_cinema' // 你的数据库名
};

// 创建数据库连接池
const pool = mysql.createPool(dbConfig);

// 用户登录接口
app.post('/api/users/login', async (req, res) => {
  try {
    const { username, password } = req.body;
    const [rows] = await pool.query(
      'SELECT * FROM users WHERE username = ? AND password = ?',
      [username, password]
    );
    
    if (rows.length > 0) {
      const user = rows[0];
      res.json({
        code: 200,
        message: "登录成功",
        data: {
          user_id: user.user_id,
          username: user.username,
          token: "mock_token_" + user.user_id
        }
      });
    } else {
      res.status(401).json({
        code: 401,
        message: "用户名或密码错误"
      });
    }
  } catch (error) {
    console.error('登录错误:', error);
    res.status(500).json({
      code: 500,
      message: "服务器错误"
    });
  }
});

// 用户注册接口
app.post('/api/users/register', async (req, res) => {
  try {
    const { username, password } = req.body;
    
    // 检查用户名是否已存在
    const [existingUsers] = await pool.query(
      'SELECT * FROM users WHERE username = ?',
      [username]
    );
    
    if (existingUsers.length > 0) {
      return res.status(400).json({
        code: 400,
        message: "用户名已存在"
      });
    }
    
    // 创建新用户
    const [result] = await pool.query(
      'INSERT INTO users (username, password) VALUES (?, ?)',
      [username, password]
    );
    
    res.json({
      code: 200,
      message: "注册成功",
      data: {
        user_id: result.insertId,
        username: username
      }
    });
  } catch (error) {
    console.error('注册错误:', error);
    res.status(500).json({
      code: 500,
      message: "服务器错误"
    });
  }
});

// 获取所有电影列表
app.get('/api/movies', async (req, res) => {
  try {
    const [rows] = await pool.query('SELECT * FROM movies');
    res.json({
      code: 200,
      message: "成功",
      data: rows
    });
  } catch (error) {
    console.error('获取电影列表错误:', error);
    res.status(500).json({
      code: 500,
      message: "服务器错误"
    });
  }
});

// 获取电影详情
app.get('/api/movies/:movie_id', async (req, res) => {
  try {
    const [rows] = await pool.query(
      'SELECT * FROM movies WHERE movie_id = ?',
      [req.params.movie_id]
    );
    
    if (rows.length > 0) {
      res.json({
        code: 200,
        message: "成功",
        data: rows[0]
      });
    } else {
      res.status(404).json({
        code: 404,
        message: "电影不存在"
      });
    }
  } catch (error) {
    console.error('获取电影详情错误:', error);
    res.status(500).json({
      code: 500,
      message: "服务器错误"
    });
  }
});

// 获取电影场次
app.get('/api/screenings/movie/:movie_id', async (req, res) => {
  try {
    const [rows] = await pool.query(
      'SELECT * FROM screenings WHERE movie_id = ?',
      [req.params.movie_id]
    );
    
    if (rows.length > 0) {
      res.json({
        code: 200,
        message: "成功",
        data: rows
      });
    } else {
      res.status(404).json({
        code: 404,
        message: "该电影暂无场次"
      });
    }
  } catch (error) {
    console.error('获取电影场次错误:', error);
    res.status(500).json({
      code: 500,
      message: "服务器错误"
    });
  }
});

// 获取场次详情
app.get('/api/screenings/:screening_id', async (req, res) => {
  try {
    const [screeningRows] = await pool.query(
      'SELECT * FROM screenings WHERE screening_id = ?',
      [req.params.screening_id]
    );
    
    if (screeningRows.length === 0) {
      return res.status(404).json({
        code: 404,
        message: "场次不存在"
      });
    }
    
    const screening = screeningRows[0];
    const [movieRows] = await pool.query(
      'SELECT title, duration FROM movies WHERE movie_id = ?',
      [screening.movie_id]
    );
    
    res.json({
      code: 200,
      message: "成功",
      data: {
        ...screening,
        movie: movieRows[0]
      }
    });
  } catch (error) {
    console.error('获取场次详情错误:', error);
    res.status(500).json({
      code: 500,
      message: "服务器错误"
    });
  }
});

// 获取当前闪购活动
app.get('/api/flash-sales/current', async (req, res) => {
  try {
    const now = new Date();
    const [rows] = await pool.query(
      `SELECT fs.*, s.screening_time, s.theater_number, m.title 
       FROM flash_sales fs
       JOIN screenings s ON fs.screening_id = s.screening_id
       JOIN movies m ON s.movie_id = m.movie_id
       WHERE fs.start_time <= ? AND fs.end_time >= ?`,
      [now, now]
    );
    
    res.json({
      code: 200,
      message: "成功",
      data: rows.map(row => ({
        flash_sale_id: row.flash_sale_id,
        screening_id: row.screening_id,
        start_time: row.start_time,
        end_time: row.end_time,
        discount: row.discount,
        screening: {
          screening_time: row.screening_time,
          theater_number: row.theater_number,
          movie: {
            title: row.title
          }
        }
      }))
    });
  } catch (error) {
    console.error('获取闪购活动错误:', error);
    res.status(500).json({
      code: 500,
      message: "服务器错误"
    });
  }
});

// 参与闪购活动
app.post('/api/flash-sales/:flash_sale_id/participate', async (req, res) => {
  try {
    const { ticket_count } = req.body;
    const flashSaleId = req.params.flash_sale_id;
    
    // 验证闪购活动是否存在
    const [saleRows] = await pool.query(
      'SELECT * FROM flash_sales WHERE flash_sale_id = ?',
      [flashSaleId]
    );
    
    if (saleRows.length === 0) {
      return res.status(404).json({
        code: 404,
        message: "闪购活动不存在"
      });
    }
    
    const sale = saleRows[0];
    
    // 模拟用户ID (实际应用中应从token获取)
    const userId = 1;
    
    // 创建新订单
    const [result] = await pool.query(
      'INSERT INTO orders (user_id, screening_id, ticket_count, order_time) VALUES (?, ?, ?, ?)',
      [userId, sale.screening_id, ticket_count, new Date()]
    );
    
    // 计算总价 (假设原价为100元)
    const totalPrice = 100 * ticket_count * sale.discount;
    
    res.json({
      code: 200,
      message: "闪购成功",
      data: {
        order_id: result.insertId,
        user_id: userId,
        screening_id: sale.screening_id,
        ticket_count: ticket_count,
        order_time: new Date(),
        total_price: totalPrice.toFixed(2)
      }
    });
  } catch (error) {
    console.error('参与闪购错误:', error);
    res.status(500).json({
      code: 500,
      message: "服务器错误"
    });
  }
});

// 获取用户订单
app.get('/api/orders/user', async (req, res) => {
  try {
    // 模拟用户ID (实际应用中应从token获取)
    const userId = 1;
    
    const [rows] = await pool.query(
      `SELECT o.*, s.screening_time, s.theater_number, m.title 
       FROM orders o
       JOIN screenings s ON o.screening_id = s.screening_id
       JOIN movies m ON s.movie_id = m.movie_id
       WHERE o.user_id = ?`,
      [userId]
    );
    
    res.json({
      code: 200,
      message: "成功",
      data: rows.map(row => ({
        order_id: row.order_id,
        user_id: row.user_id,
        screening_id: row.screening_id,
        ticket_count: row.ticket_count,
        order_time: row.order_time,
        screening: {
          screening_time: row.screening_time,
          theater_number: row.theater_number,
          movie: {
            title: row.title
          }
        }
      }))
    });
  } catch (error) {
    console.error('获取用户订单错误:', error);
    res.status(500).json({
      code: 500,
      message: "服务器错误"
    });
  }
});

// 取消订单
app.post('/api/orders/:order_id/cancel', async (req, res) => {
  try {
    const orderId = req.params.order_id;
    
    // 模拟用户ID (实际应用中应从token获取)
    const userId = 1;
    
    // 检查订单是否存在且属于当前用户
    const [orderRows] = await pool.query(
      'SELECT * FROM orders WHERE order_id = ? AND user_id = ?',
      [orderId, userId]
    );
    
    if (orderRows.length === 0) {
      return res.status(404).json({
        code: 404,
        message: "订单不存在或不属于当前用户"
      });
    }
    
    // 删除订单
    await pool.query(
      'DELETE FROM orders WHERE order_id = ?',
      [orderId]
    );
    
    res.json({
      code: 200,
      message: "订单取消成功",
      data: null
    });
  } catch (error) {
    console.error('取消订单错误:', error);
    res.status(500).json({
      code: 500,
      message: "服务器错误"
    });
  }
});

app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});